<?php
namespace frontend\controllers;

use common\models\Sign;
use frontend\models\SignForm;
use Yii;
use yii\web\Controller;


/**
 * Site controller
 */
class SiteController extends Controller
{

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('show');
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionShow()
    {
        return $this->render('show');
    }

    public function actionShare()
    {
        return $this->render('share');
    }

    public function actionSign()
    {
        if (Yii::$app->request->isPost) {
            $model = new SignForm();
            if ($result = $model->submit(Yii::$app->request->post())) {
                $data = [
                    'success' => 'ok',
                    'data' => $result->toArray(),
                ];
            } else {
                $data = [
                    'success' => 'no',
                    'msg' => $model->getFirstError('number')
                ];
            }
            return json_encode($data);
        }
        return $this->render('sign');
    }

    public function actionSuccess()
    {
        $data['sort'] = Yii::$app->request->get('sort');
        $app = Yii::$app->wechat->official;
        $config = $app->jssdk->buildConfig(['onMenuShareAppMessage', 'onMenuShareTimeline']);
        $data['config'] = $config;
        $model = Sign::findOne(['sort' => $data['sort']]);
        return $this->render('success', ['data' => $data, 'model' => $model]);
    }

    public function actionSearch()
    {
        $keywords = Yii::$app->request->post('keywords');
        if ($keywords) {
            $model = Sign::find()->where(['number' => $keywords])->one();
        }

        $data = [
            'keywords' => $keywords,
            'model' => $model
        ];
        return $this->render('search', $data);
    }

    public function actionOauthCallback()
    {
        $app = Yii::$app->wechat->official;
        $user = $app->oauth->user();
        Yii::$app->session->set('wechat_user', $user->toArray());
        return Yii::$app->response->redirect(Yii::$app->session->get('target_url'))->send();
    }

}
